package cn.itcast.web.utils;

import cn.itcast.domain.system.SysLog;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.SysLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

@Component
@Aspect
public class LogAspect {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpSession session;

    @Autowired
    private SysLogService sysLogService;

    @Around("execution(* cn.itcast.web.controller.*.*.*(..)) && !execution(* cn.itcast.web.controller.system.SysLogController.*(..))")
    public Object saveLog(ProceedingJoinPoint pj) {

        try {
            Object result = pj.proceed();
            SysLog sysLog = new SysLog();

            //sysLog.setId(UUID.randomUUID().toString());//sysLogService的save方法中已设置
            User user = (User) session.getAttribute("loginUser");
            sysLog.setUserName(user.getUserName());
            sysLog.setIp(request.getRemoteAddr());//获取客户端ip
            sysLog.setTime(new Date());
            sysLog.setMethod(pj.getSignature().getName());//获取该方法签名，再得到其姓名
            sysLog.setAction(pj.getTarget().getClass().getName());//得到调用的controller类名
            sysLog.setCompanyId(user.getCompanyId());
            sysLog.setCompanyName(user.getCompanyName());

            sysLogService.save(sysLog);

            return result;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            throw new RuntimeException(throwable);
        }
    }
}
